The student Vasya has a younger brother,
Peter, who went to the first grade and began learning arithmetic. For homework
in the first grade, he was assigned numerous problems involving addition and
subtraction. Peter asked Vasya to check his homework. Upon seeing the two-page
scribbled tests, Vasya was horrified by the workload and decided to teach Peter
to use a computer for self-checking. To accomplish this, Vasya needs to write a
program that computes the answers to the required arithmetic problems.
Input. One line
contains numbers and symbols ‘+’ and ‘-’. The length of
the line does not exceed 10000 characters, and the values of all numbers are not greater than 10000.
Output. Print one
integer – the result of the calculation.
Sample
input |
Sample
output |
1+22-3+4-5+123 |
142 |
SOLUTION
strings
Algorithm analysis
Read the first
term into the variable res. Next, split the remaining
line into pairs: an operator symbol and a term.
Sequentially read
the pairs
(character, number) until the end of the
file, performing the corresponding operations.
Read the first term into the variable res.
scanf("%d",&res);
Read the operation sign ch (addition or subtraction), followed by an integer x. Add x to
or subtract it from the total result res.
while (scanf("%c%d", &ch, &x) == 2)
if (ch == '+') res += x; else res -= x;
Print the result of the computations.
printf("%d\n",res);
Read the first term into the variable res.
cin >> res;
Continue the loop until the next character
is not the end-of-line character ‘\n’. The peek function returns the
next character from the input stream without extracting it.
while(cin.peek() != '\n')
{
Read the operation sign ch (addition or subtraction), followed by an integer x. Add x to
or subtract it from the total result res.
cin >> ch >> x;
if (ch == '+') res
+= x; else
res -= x;
}
Print the result of the computations.
cout << res << endl;
Java implementation
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner con = new Scanner(System.in);
String s = con.nextLine();
StringTokenizer st1 = new StringTokenizer(s, "+-");
StringTokenizer st2 = new StringTokenizer(s, "0123456789");
int res = Integer.parseInt(st1.nextToken());
while (st1.hasMoreTokens())
{
int x = Integer.parseInt(st1.nextToken());
if (st2.nextToken().equals("+")) res += x;
else res -= x;
}
System.out.println(res);
con.close();
}
}
Python implementation
Compute the
value of the input expression and print the result.
·
The eval()
function evaluates a string as a Python expression and returns the result.
print(eval(input()))